package com.ruo.usercenter.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruo.usercenter.common.ErrorCode;
import com.ruo.usercenter.exception.BusinessException;
import com.ruo.usercenter.mapper.UserMapper;
import com.ruo.usercenter.pojo.User;
import com.ruo.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ruo.usercenter.constant.UserConstant.DEAFULT_ROLE;
import static com.ruo.usercenter.constant.UserConstant.USER_LOGIN_STATA;

/**
* @author 28724
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2023-05-24 18:59:32
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "ruo";
    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword, String userCode) {
        //1.判断账户是否为空
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,userCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户，密码，确认密码，员工编号存在空值");
        }
        //判断账户是否不小于4位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于4位");
        }
        //判断密码是否小于8位
        if (userPassword.length() < 6 || checkPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码小于8位");
        }
        //4判断密码是否含有特殊字符
        String validPattern = "[` ~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码包含特殊字符");
        }
        //判断密码是否相等
        if (!(userPassword.equals(checkPassword))){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }
        //判断账户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"当前账户存在");
        }
        //判断用户编号
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_code",userCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"当前编号已存在");
        }
        //2.密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //插入书记
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserCode(userCode);
        user.setUserRole(DEAFULT_ROLE);
        int saveResult = userMapper.insert(user);
        if (saveResult != 1){
            return (long)-1;
        }

        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.判断账户是否为空
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户，密码存在空值");
        }
        //2判断账户是否不小于4位
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于4位");
        }
        //3判断密码是否小于8位
        if (userPassword.length() < 6){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码小于8位");
        }
        //4判断密码是否含有特殊字符
        String validPattern = "[` ~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码包含特殊字符");
        }
        //4验证账户是否在
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_account",userAccount);
        queryWrapper.eq("user_password",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"登陆失败");
        }
        //5脱敏
        User saftyUser = getSaftyUser(user);
        //6记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATA,user);
        return saftyUser;
    }

    public User getSaftyUser(User user){
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"获取用户失败");
        }
        User saftyUser = new User();
        saftyUser.setId(user.getId());
        saftyUser.setUsername(user.getUsername());
        saftyUser.setUserAccount(user.getUserAccount());
        saftyUser.setAvatarUrl(user.getAvatarUrl());
        saftyUser.setGender(user.getGender());
        saftyUser.setPhone(user.getPhone());
        saftyUser.setEmail(user.getEmail());
        saftyUser.setUserCode(user.getUserCode());
        saftyUser.setUserRole(user.getUserRole());
        saftyUser.setUserStatus(user.getUserStatus());
        saftyUser.setCreateTime(user.getCreateTime());
        return saftyUser;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    public int userLoginOut(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATA);
        return 0;
    }

}




